package com.mywork.controller;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimpleDataFormatSerializer;
import com.mywork.po.Curelist;
import com.mywork.po.Page;
import com.mywork.po.Sign;
import com.mywork.po.User;
import com.mywork.po.User_profession;
import com.mywork.service.CureListService;
import com.mywork.service.DrugService;
import com.mywork.service.MD5;
import com.mywork.service.MyJSONUtil;
import com.mywork.service.ShowInformation;
import com.mywork.service.SignService;
import com.mywork.service.UserService;
@SessionAttributes("permission")
@Controller
@RequestMapping("/superUser")
public class SuperUserController {
	@Autowired
	UserService userService;

	@Autowired
	CureListService cureService;

	@Autowired
	DrugService drugService;

	@Autowired
	SignService signService;
	
	@ModelAttribute
	public void init(User user, Model model, Curelist cureList,Sign sign) {

		if (user == null) {
			model.addAttribute("user", new User());

		}
		if (cureList == null) {
			model.addAttribute("cureList", new Curelist());
		}
		if(sign==null){
			model.addAttribute("sign", sign);
		}

	}

	@RequestMapping("/getUsers")
	
	public String getUsers(String pageNo, Model model, HttpServletRequest request,@ModelAttribute("permission")int permission) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		Page page = new Page();
		if (pageNo == null || pageNo.trim() == "") {
			page.setPageNo(0);
		} else {
			page.setPageNo(Integer.valueOf(pageNo).intValue());
		}
		page.setPageSize(10);
		List<User_profession> users = userService.getUsers(page);
		int count=userService.getCountOfUser();
		page.setTotalRecords(count);
		model.addAttribute("allPageNum", page.getTotalPage());
		model.addAttribute("users", users);
		
		return "/user/userList";
	}

	// @RequestParam("参数名") 注释是用来提取获取的参数的，
	@RequestMapping("/addUser")
	public String addUser(User user, Model model, HttpServletRequest request,@ModelAttribute("permission")int permission) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		
		if (user.getUserid() == null || user.getUserid() == "") {
			return "/user/addUser";
		}
		
		if(userService.isExist(user.getUserid())){
			ShowInformation.forInformation(model, "帐号已经存在", "返回", request.getContextPath()+"/superUser/addUser", 1);
			return "/information";

		}
		try {
			user.setPassword(MD5.getMD5String(user.getPassword()));
		} catch (NoSuchAlgorithmException e) {
			// TODO 自动生成的 catch 块
			ShowInformation.forInformation(model, "出错了", "返回", request.getContextPath()+"/superUser/addUser", 1);
			e.printStackTrace();
			return "/information";

		}
		
		user.setIsrecipe(true);

		
		
		userService.addUser(user);
		
		model.addAttribute("information", "添加成功");
		model.addAttribute("buttonName", "返回");
		model.addAttribute("buttonAddress", request.getContextPath()+"/superUser/addUser");
		model.addAttribute("buttonClass", "alert-success");
		return "/information";

	}

	@RequestMapping("/deleteUser")
	public String deleteUser(String userId, Model model, HttpServletRequest request,@ModelAttribute("permission")int permission) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		
		userService.delete(userId);
		model.addAttribute("yes", "删除成功");
		ShowInformation.forInformation(model, "删除成功", "返回", request.getContextPath()+"/superUser/getUsers", 4);
		return "information";
	}

	@RequestMapping("/updateUser")
	public String updateUser(String userId, Model model, HttpServletRequest request,User user,@ModelAttribute("permission")int permission) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		if(user.getUserid()==null||user.getUserid()==""){
			if(userId==null){
				return "/user/userList";
			}else{
				User editUser=userService.selectById(userId);
				model.addAttribute("user", editUser);
				return "/user/modifyUserMessage";
			}
		}else{
			try {
				user.setPassword(MD5.getMD5String(user.getPassword()));
			} catch (NoSuchAlgorithmException e) {
				// TODO 自动生成的 catch 块
				ShowInformation.forInformation(model, "修改失败", "返回", request.getContextPath()+"/superUser/getUsers", 1);
				return "information";
			}
			userService.updateUser(user);
			ShowInformation.forInformation(model, "修改成功", "返回", request.getContextPath()+"/superUser/getUsers", 4);
			return "information";
		}
		
		
		
	}

	@RequestMapping("/addCureList")
	public String addCureList(Curelist cureList, Model model, HttpServletRequest request,User user,@ModelAttribute("permission")int permission) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		if(cureList.getCurename()!=null){
			if(cureList.getPrice()==0.00){
				cureList.setCurecan(false);
			}else{
				cureList.setCurecan(true);
			}
			
			cureService.addCure(cureList);
			ShowInformation.forInformation(model, "添加成功", "返回", request.getContextPath()+"/superUser/addCureList", 4);
			return "information";
			
		}else{
			List<Curelist> cureListsForLevelOne= cureService.getCureListByLevel(1);
			model.addAttribute("cureListsForLevelOne", cureListsForLevelOne);
			model.addAttribute("cureList", new Curelist());
			return "/project/addProject";
		}
		
	}

	@RequestMapping("/getCureList")
	public String getCureList(Model model, String pageNo, HttpServletRequest request,User user,@ModelAttribute("permission")int permission) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		Page page = new Page();
		if (pageNo == null || pageNo == "") {
			page.setPageNo(0);
		}else{
			page.setPageNo(Integer.valueOf(pageNo).intValue());
		}
		page.setPageSize(10);
		
		List<Curelist> cureLists = cureService.getCureLists(page);
		int count=cureService.getCountOfCureList();
		page.setTotalRecords(count);
		model.addAttribute("cureLists", cureLists);
		model.addAttribute("allPageNum", page.getTotalPage());
		return "/project/projectList";
	}

	@RequestMapping("/delectCureList")
	public String delectCureList(String cureId, Model model,@ModelAttribute("permission")int permission, HttpServletRequest request) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		
		cureService.delectCure(cureId);
		ShowInformation.forInformation(model, "删除成功", "返回", request.getContextPath()+"/superUser/getCureList", 4);
		return "information";
	}

	@RequestMapping("/updateCureList")
	public String updateCureList(String cureId,Curelist cureList, Model model,HttpServletRequest request,@ModelAttribute("permission")int permission) {
		User rowUser = (User) request.getSession().getAttribute("user");
		if (rowUser == null||permission!=5) {
			return "login";
		}
		if(cureList.getCureid()!=null){
			
			if(cureList.getPrice().equals(0.00)){
				cureList.setCurecan(true);
			}else{
				cureList.setCurecan(false);
			}
			cureService.updateCure(cureList);
			ShowInformation.forInformation(model, "修改成功","返回", request.getContextPath()+"/superUser/getCureList", 4);
			return "information";
		}else{
			Curelist curelist=cureService.getCureListByCureListId(cureId);
			model.addAttribute("cureList", curelist);
			return "/project/modifyProject";
		}
		
		
		
	}
	/**
	 * 下面是处理体格诊断的
	 */
	@RequestMapping("/addSign")
	public String addSign(Model model,HttpServletRequest request,Sign sign,@ModelAttribute("user")User user,@ModelAttribute("permission")int permission){
		if(user==null||permission!=5){
			return "login";
		}
		if(sign.getSign()==null||sign.getSign().trim()==""){
			List<Sign> signForLevel1=signService.getSignForLastSignId(-1);
			model.addAttribute("signForLevel1", signForLevel1);
			return "/project/addPhysicalExamination";
		}else{
			signService.addSign(sign);
			ShowInformation.forInformation(model, "添加体格诊断成功", "返回", request.getContextPath()+"/superUser/addSign", 4);
			return "information";
		}
	}
	
	@RequestMapping("/getSigns")
	public String getSigns(String pageNo,@ModelAttribute("permission")int permission,@ModelAttribute("user")User user,Model model,HttpServletRequest request){
		if(user==null||permission!=5){
			return "";
		}
		Page page = new Page();
		if(pageNo==null||pageNo==""){
			page.setPageNo(0);
		}else{
			page.setPageNo(Integer.valueOf(pageNo).intValue());
		}
		page.setPageSize(10);
		page.setTotalRecords(signService.getCountOfSign());
		List<Sign> signs = signService.getAllSignByPage(page);
		model.addAttribute("signs", signs);
		model.addAttribute("allPageNo", page.getTotalPage());
		return "/project/physicalExaminationList";
	}
	
	
	@RequestMapping("deleteSign")
	public String deleteSign(String signId ,@ModelAttribute("user")User user,@ModelAttribute("permission")int permission,Model model,HttpServletRequest request){
		if(user==null||permission!=5){
			return "login";
		}
		signService.delete(signId);
		ShowInformation.forInformation(model, "删除成功","返回", request.getContextPath()+"/superUser/getSigns", 4);
		return "information";
		
	}
	
	@RequestMapping("updateSign")
	public String updateSign(String signId,Sign sign,@ModelAttribute("user")User user,@ModelAttribute("permission")int permission,Model model,HttpServletRequest request){
		if(user==null||permission!=5){
			return "login";
		}
		if(sign.getSign()==null||sign.getSign().trim()==""){
			Sign rowSign = signService.getSign(signId);
			model.addAttribute("sign", rowSign);
			return "/project/modifyPhysicalExamination";
		}else{
			signService.updateSign(sign);
			ShowInformation.forInformation(model, "修改成功", "返回",request.getContextPath()+"/superUser/getSigns", 4);
			return "information";
		}
	}
	
	/**
	 * 设置AJAX接口返回json数据
	 * @param drugId
	 * @param response
	 */
	@RequestMapping("/forAjax")
	public void forAjax(String lastCureId, HttpServletResponse response,HttpServletRequest request) {
		//还没加验证
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = MyJSONUtil.getJSONprintWriter(response);
		List<Curelist> cureListForLastCureId= cureService.getCureListByLastCureId(lastCureId);
//		
//		char[] json = JSON.toJSON(cureListForLastCureId).toString().toCharArray();
//		StringBuffer sb = new StringBuffer();
//		for(char s:json){
//			if(s=='"'){
//				sb.append('\\');
//				sb.append(s);
//			}else{
//				sb.append(s);
//			}
//		}
		out.print(JSON.toJSON(cureListForLastCureId).toString());
		out.flush();
		out.close();

	}

	
	
	/**
	 * 设置绑定器
	 * @param binder
	 * @throws ServletException
	 */
	 @InitBinder
	    protected void initBinder(
	            WebDataBinder binder) throws ServletException {
	       
	         
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	                dateFormat.setLenient(false);
	                binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	                
	               
	    }
	/**
	 * @param response
	 * @return
	 */

}
